package com.mc.book.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpLoadBookUtil {

    public static String upLoadBook(String book_name){
        String reqUrl = "http://10.0.24.13:8999/book/system/book/addByAi";
        JSONObject json = new JSONObject();
        json.put("book_name",book_name);
        String result = null;
        try {
            result = getURLByPost(reqUrl,json.toJSONString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public static String upLoadFile(MultipartFile file){
        try {
            String reqUrl = "http://10.0.24.13:8999/book/common/upload";

            // 服务器接收文件的URL
            URL url = new URL(reqUrl); // 替换为你的接口URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            String boundary = "------WebKitFormBoundary7MA4YWxkTrZu0gW"; // 自定义的请求边界字符串
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            OutputStream outputStream = connection.getOutputStream();
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);

            // 添加文件字段
            addMultipartFile(writer, outputStream, boundary, "file", file);

            // 结束请求部分
            writer.append("--").append(boundary).append("--").append("\r\n");
            writer.flush();
            writer.close();

            // 检查服务器响应
//            int responseCode = connection.getResponseCode();
//            System.out.println("Response Code: " + responseCode);

            // 读取服务器的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

//            System.out.println("Response: " + response.toString());
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void addMultipartFile(PrintWriter writer, OutputStream outputStream, String boundary, String fieldName, MultipartFile multipartFile) throws IOException {
        String fileName = multipartFile.getOriginalFilename();
        writer.append("--").append(boundary).append("\r\n");
        writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"\r\n");
        writer.append("Content-Type: ").append(multipartFile.getContentType()).append("\r\n");
        writer.append("Content-Transfer-Encoding: binary\r\n");
        writer.append("\r\n");
        writer.flush();

        InputStream inputStream = multipartFile.getInputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();

        writer.append("\r\n");
        writer.flush();
    }

    public static String getURLByPost(String urlStr,String params)throws Exception{
        URL url=new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "application/json");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
        printWriter.write(params);
        printWriter.flush();
        BufferedReader in = null;
        StringBuilder sb = new StringBuilder();
        try{
            in = new BufferedReader( new InputStreamReader(conn.getInputStream(),"UTF-8") );
            String str = null;
            while((str = in.readLine()) != null) {
                sb.append( str );
            }
        } catch (Exception ex) {
            throw ex;
        } finally{
            try{
                conn.disconnect();
                if(in!=null){
                    in.close();
                }
                if(printWriter!=null){
                    printWriter.close();
                }
            }catch(IOException ex) {
                throw ex;
            }
        }
        return sb.toString();
    }


}
